package com.smg.community.controller;

import static com.smg.community.util.ProjectUtil.getRegTargetType;
import cn.jpush.api.MessageResult;
import cn.org.rapid_framework.page.Page;
import com.google.gson.Gson;
import com.smg.community.model.SmgAndroidVersion;
import com.smg.community.model.SmgAppSuggestion;
import com.smg.community.model.SmgCarBrand;
import com.smg.community.model.SmgCarModels;
import com.smg.community.model.SmgMember;
import com.smg.community.model.SmgMemberBehavior;
import com.smg.community.model.SmgMemberBehaviorComment;
import com.smg.community.model.SmgMemberFocus;
import com.smg.community.model.SmgMemberFriend;
import com.smg.community.model.SmgMemberReport;
import com.smg.community.model.SmgMessage;
import com.smg.community.model.SmgPoi;
import com.smg.community.model.SmgPoiCheckin;
import com.smg.community.model.SmgRegVerifycodeRecord;
import com.smg.community.model.TalkHistory;
import com.smg.community.service.HttpRequestProxy;
import com.smg.community.service.SmgMemberBehaviorCommentManager;
import com.smg.community.service.SmgMemberBehaviorManager;
import com.smg.community.service.SmgMemberFocusManager;
import com.smg.community.service.SmgMemberFriendManager;
import com.smg.community.service.SmgMemberManager;
import com.smg.community.service.SmgMessageManager;
import com.smg.community.service.SmgPoiCheckinManager;
import com.smg.community.service.SmgPoiManager;
import com.smg.community.setting.ProjectSetting;
import com.smg.community.thread.SaveNearByMajiaThread;
import com.smg.community.util.Constant;
import com.smg.community.util.DateFormatUtil;
import com.smg.community.util.GsonUtil;
import com.smg.community.util.ImageUtil2;
import com.smg.community.util.ProjectUtil;
import com.smg.community.util.StringUtil;
import com.smg.community.vo.query.SmgMemberBehaviorCommentQuery;
import com.smg.community.vo.query.SmgMemberBehaviorQuery;
import com.smg.community.vo.query.SmgMemberQuery;
import com.smg.community.vo.query.SmgMessageQuery;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javacommon.base.BaseQuery;
import javacommon.base.BaseRestSpringController;
import javacommon.util.FileUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping({"/"})
@Transactional
public class RequestController extends BaseRestSpringController<SmgMember, Integer>
{
  private static Properties p = FileUtil.loadProperties("config.properties");
  public static String accountId;
  public static String pwd = p.getProperty("pwd");
  public static String REG_LOGIN_SEVICE_URL;
  private static final long serialVersionUID = 1L;
  
  public static HashMap<String,String> memberIdDeviceIdMap = new HashMap<String,String>(2000);
  
  private static HashMap<String,String> memberTokenMap = new HashMap<String,String>(2000);
  Log logger = LogFactory.getLog(RequestController.class);

  static
  {
    accountId = p.getProperty("accountId");
    REG_LOGIN_SEVICE_URL = p.getProperty("REG_LOGIN_SEVICE_URL");
  }
  
  public static String hideMobileNumber(String mobileNumber){
	  String pre  = mobileNumber.substring(0,4);
	  String end = mobileNumber.substring(7,mobileNumber.length());
	  return pre +"****"+end;
  }
  public static String hideEmail(String email){
	  int index = email.indexOf("@");
	  String pre  = email.substring(0,1);
	  String end = email.substring(index,email.length());
	  return pre +"****"+end;
  }

  @RequestMapping({"/login"})
  @ResponseBody
  public Map<String, Object> login(@RequestParam String loginName, @RequestParam String password,@RequestParam String versionCode,
		  @RequestParam String uuid)
  {
    String md5Password = StringUtil.getMD5Str(password);
    Map map = new HashMap();
    SmgMember member = null;
    /*本地登录代码去掉
    try
    {
    	member = this.smgMemberManager.getByLoginNameAndPassword(loginName, md5Password);
      if (member == null){
    	  
      }
      else{
		      map.put("state", "1");
      }
    }
    catch (Exception e) {
      e.printStackTrace();
      map.put("state", "-99");
      map.put("desc", "运行时错误");
      return map;
    }
 */
	    int type = ProjectUtil.getLoginNameType(loginName);
	
	    String loginUrl = REG_LOGIN_SEVICE_URL + "/account/login.action";
	    try
	    {
			      if (type == Constant.INVALID_LOGINNAME) {
			        map.put("state", "-3");
			        map.put("desc", "登录名格式不正确");
			        return map;
			      }
			      Map paramMap = new HashMap();
			      paramMap.put("username", loginName);
			      paramMap.put("type", type);
			      paramMap.put("passwd", password);
			      Gson gson = new Gson();
			      String param = gson.toJson(paramMap);
			      loginUrl = loginUrl + "?param=" + param;
			      this.logger.debug(loginUrl);
			      String loginResult = HttpRequestProxy.doGet(loginUrl, "UTF-8");
			      if (loginResult == null) {
			        map.put("state", "-1");
			        map.put("desc", "调用接口返回的值为null");
			        return map;
			      }
			      Map<String,String> loginResultMap = GsonUtil.getMapByJsonString(loginResult);
			      if (((String)loginResultMap.get("resultCode")).equals("0"))
			      {
				        member = new SmgMember();
				        member.setAppSource(null);
				        member.setAppVersion(null);
				        if (type == 2) {
				          member.setEmail(loginName);
				          member.setIsEmailVerify(1);
				          member.setIsMobileVerify(Integer.valueOf(0));
				        } else if (type == 1) {
				          member.setMobileNumber(loginName);
				          member.setIsMobileVerify(1);
				          member.setIsEmailVerify(Integer.valueOf(0));
				        }
				        member.setHeadImage(null);
				        member.setLastLoginDate(new Date());
				        member.setLoginName(loginName);
				        String nickName =  (String)loginResultMap.get("nickName");
				        if ( nickName == null || nickName.equals("")){
				        	//2:手机号
				    		//3:邮箱
				        	if ( type == 2){
				        		try{
				        			nickName = hideMobileNumber(loginName);
				        		}catch(Exception e){
				        			e.printStackTrace();
				        		}
				        	}else if ( type == 3 ){
				        		try{
				        			nickName = hideEmail(loginName);
				        		}catch(Exception e){
				        			e.printStackTrace();
				        		}
				        	}
				        }
				        member.setNickName( nickName);
				        member.setPassword(StringUtil.getMD5Str(password));
				        member.setRegDate(new Date());
				        member.setRegSource("mobile");
				        member.setSex("m");
				        member.setSignature(null);
				        member.setThirdPartyToken(null);
				        member.setTopicCount(Integer.valueOf(0));
				        member.setIsNewMember(0);
				        member.setNickNameFirstChar(cn2FirstSpell(nickName));
				        SmgMember tmp =  null;
						if ( type > 1 ){
							tmp = smgMemberManager.getByLoginName(loginName);
						}else {
							tmp = smgMemberManager.getByNickname(loginName);
						}
						if ( tmp  == null ){
							smgMemberManager.save(member);
						}else{
							member = tmp;
							member.setNickName(nickName);
						}
						memberTokenMap.put(member.getMemberId()+"", loginResultMap.get("token"));
				        map.put("state", "1");
				        map.put("desc", loginResultMap.get("resultMsg"));
				    	member.setTakeId(member.getMemberId().intValue() + 10000);
				        member.setUnReadMessageCount(smgMessageManager.getUnReadMessageCount(member.getMemberId()));
				        member.setUnReadSystemMessageCount(smgMessageManager.getUnReadSystemMessageCount(member.getMemberId()));
			        if (member.getBirthYear() == 0) {
			          member.setAge(25);
			        } else {
			          int year = Calendar.getInstance().get(1);
			          member.setAge(year - member.getBirthYear());
			        }
			        SmgMemberBehavior behavior = this.smgMemberBehaviorManager.getLastestByMemberId(member.getMemberId()+"");
			        if (behavior == null)
			          member.setLastestBehavior("暂无动态");
			        else {
			          member.setLastestBehavior(behavior.getCont());
			          member.setLastBehaviorId(behavior.getBehaviorId()+"");
			        }
			        List<SmgMember> friendList = smgMemberManager.getFriendMemberListByMemberId(member.getMemberId()+"",0,10);
			    	map.put("member",member);
			    	map.put("friendList",friendList);
			    	 SmgMessageQuery query = new SmgMessageQuery();
			         query.setToIsValid(1);
			         query.setIsRead(0);
			         query.setToIsValid(1);
			         query.setToMemberId(member.getMemberId());
			         setStartAndLimit(query, 1, 20);
			         Page page = this.smgMessageManager.findPage(query);
			      	map.put("unReadMessageList",page.getResult());
			      	SmgMemberBehaviorQuery query2 = new SmgMemberBehaviorQuery();
			        query2.setPageNumber(1);
			        query2.setIsFriend(member.getMemberId()+"");
			        setStartAndLimit(query, 1, 20);
			        Page behaviorPage = this.smgMemberBehaviorManager.findPage(query2);
			     	map.put("behaviorList",behaviorPage.getResult());
			     	boolean hasNewVersion  = false;
			    	SmgAndroidVersion version = smgAndroidVersionManager.getByVersionCode(versionCode);
			    	if ( version != null){
			    		SmgAndroidVersion newVersion   = smgAndroidVersionManager.getNewVersion(version.getId());
			    		if ( newVersion != null){
			    			hasNewVersion = true;
			    			map.put("newVersion",newVersion);
			    		}
			    	}
			    	uuid = uuid.replaceAll("-","");
			    	smgMemberManager.updateuuid(member.getMemberId(),uuid);
			    	smgMemberManager.updateNickname(member.getMemberId(), nickName);
					smgMemberManager.updateNicknameFirstchar(member.getMemberId(), cn2FirstSpell(nickName));
			    	memberIdDeviceIdMap.put(member.getMemberId()+"", uuid);
			    	map.put("hasNewVersion",hasNewVersion);
			      }else{
			    	  map.put("state", "-1");
				      map.put("desc", "登录失败,用户名或者密码不正确");
				      return map;
			      }
			     

	    }
	    catch (Exception e)
	    {
	      e.printStackTrace();
	      map.put("state", "-99");
	      map.put("desc", "运行时错误");
	      return map;
	    }
	     return map;
  }

  @RequestMapping({"/getverifycode"})
  @ResponseBody
  public Map<String, Object> getVerifyCode(@RequestParam String nickName, @RequestParam String loginName, @RequestParam String password)
  {
    Map map = new HashMap();

    int type = ProjectUtil.getRegTargetType(loginName);
    try {
      this.logger.debug(Boolean.valueOf(type == Constant.INVALID_LOGINNAME));
      if (type == Constant.INVALID_LOGINNAME) {
        map.put("state", "-3");
        map.put("desc", "登录名格式不正确");
        return map;
      }
      String preRegUrl = REG_LOGIN_SEVICE_URL + "/account/register.action";
      Map paramMap = new HashMap();
      paramMap.put("type", type +"");
      paramMap.put("passwd", password);
      paramMap.put("nickName", nickName);
      paramMap.put("target", loginName);
      Gson gson = new Gson();
      String param = gson.toJson(paramMap);
      preRegUrl = preRegUrl + "?param=" + param;
      this.logger.debug(preRegUrl);
      String result = HttpRequestProxy.doGet(preRegUrl, "UTF-8");
      if (result == null) {
        map.put("state", "-1");
        map.put("desc", "调用接口返回的值为null");
      } else {
        Map preRegMap = GsonUtil.getMapByJsonString(result);
        if (((String)preRegMap.get("resultCode")).equals("0")) {
          map.put("state", "1");
          map.put("desc", "调用接口成功");
        } else {
          map.put("state", "-2");
          map.put("desc", preRegMap.get("resultMsg"));
        }
      }

      return map;
    } catch (Exception e) {
      e.printStackTrace();
      map.put("state", "-99");
      map.put("desc", "运行时错误"); }
    return map;
  }

  @RequestMapping({"/reg"})
  @ResponseBody
  public Map<String, Object> reg(@RequestParam String nickName, @RequestParam String loginName, @RequestParam String password, @RequestParam String verifyCode, @RequestParam String appSource, @RequestParam String appVersion, @RequestParam String regSource)
  {
    Map map = new HashMap();
    Map paramMap = new HashMap();
    int type = ProjectUtil.getRegTargetType(loginName);
    if (type == Constant.INVALID_LOGINNAME) {
    }
    paramMap.put("nickName", nickName);
    paramMap.put("password", password);
    paramMap.put("target", loginName);
    paramMap.put("type", ProjectUtil.getRegTargetType(loginName));
    paramMap.put("verCode", verifyCode);
    Gson gson = new Gson();
    String param = gson.toJson(paramMap);
    String addMemberUrl = REG_LOGIN_SEVICE_URL + "/account/addAccount.action?param=" + param;
    this.logger.debug(addMemberUrl);
    String addMemberResult = HttpRequestProxy.doGet(addMemberUrl, "UTF-8");
    if (addMemberResult == null) {
      map.put("state", "-1");
      map.put("desc", "注册失败");
    } else {
      Map addMemberMap = GsonUtil.getMapByJsonString(addMemberResult);
      if (((String)addMemberMap.get("resultCode")).equals("0"))
      {
        SmgMember member = new SmgMember();
        member.setAppSource(appSource);
        member.setAppVersion(appVersion);
        if (type == 2) {
          member.setEmail(loginName);
          member.setIsEmailVerify(1);
          member.setIsMobileVerify(Integer.valueOf(0));
        } else if (type == 1) {
          member.setMobileNumber(loginName);
          member.setIsMobileVerify(1);
          member.setIsEmailVerify(Integer.valueOf(0));
        }
        member.setHeadImage(null);

        member.setLastLoginDate(new Date());
        member.setLoginName(loginName);
        member.setNickName(nickName);
        member.setPassword(StringUtil.getMD5Str(password));
        member.setRegDate(new Date());
        member.setNickNameFirstChar(cn2FirstSpell(nickName));
        member.setRegSource(regSource);
        member.setSex("m");
        member.setSignature("");
        member.setThirdPartyToken(null);
        member.setTopicCount(Integer.valueOf(0));
        member.setIsNewMember(1);
        try
        {
          this.smgMemberManager.save(member);
        } catch (Exception e) {
          e.printStackTrace();
        }
        map.put("member", member);
        map.put("state", "1");
        map.put("desc", "调用接口成功");
      }
      else {
        map.put("state","-2");
        map.put("desc", addMemberMap.get("resultMsg"));
      }
    }
    return map;
  }

  @RequestMapping({"/sendsms"})
  @ResponseBody
  public Map<String, Object> sendSms(@RequestParam String mobilenumber, @RequestParam String message)
  {
    String timestamp = DateFormatUtil.getDateStr("yyyyMMddHHmmss");
    
    String newpwd = StringUtil.getMD5Str(pwd + timestamp);
    this.logger.debug(newpwd);
    newpwd = newpwd.toUpperCase();
    this.logger.debug(newpwd);
    try
    {
      message = URLEncoder.encode(message, "GBK");
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    String r = HttpRequestProxy.doPost("http://221.181.73.88/sms/SmsSendInstance.do?accountId=" + accountId + "&pwd=" + newpwd + "&mobs=" + mobilenumber + "&msg=" + message + "&timestamp=" + timestamp, new HashMap(), "utf-8");
    this.logger.debug(r);
    Map resultMap = new HashMap();
    resultMap.put("result", r);
    return resultMap;
  }

  public static void main(String[] arg) throws UnsupportedEncodingException {
	  System.out.println( hideEmail("sambean@126.com"));
  }

  private static boolean isChinese(char c)
  {
    Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);

    return ((ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) || 
      (ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS) || 
      (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) || 
      (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B) || 
      (ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION) || 
      (ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) || 
      (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION));
  }

  public static boolean isChinese(String strName)
  {
    char[] ch = strName.toCharArray();

    for (int i = 0; i < ch.length; ++i)
    {
      char c = ch[i];

      if (isChinese(c))
      {
        return true;
      }

    }

    return false;
  }


  @RequestMapping({"/listNearbyMember"})
  @ResponseBody
  public Map<String, Object> listNearbyMember(@RequestParam Float gpsLatitude, @RequestParam Float gpsLongitude, @RequestParam int scope, @RequestParam String pageNumber, 
		  
		  @RequestParam(required=false) String sex,
		  @RequestParam(required=false) String memberId,
		  @RequestParam(required=false) String memberCarType)
  {
	  System.out.println("nearbymember memberId"+memberId+" gpsLongitude : "+gpsLongitude +"  gpsLatitude:"+gpsLatitude);
    Map resultMap = new HashMap(); 
    try {
    	//memberCarType "" 是全部  1是车主 2是车友
      List<SmgMember> memberList = this.smgMemberManager.getNerybyMember(gpsLatitude, gpsLongitude, scope, Integer.parseInt(pageNumber), sex,memberCarType,memberId );

      boolean hasNextPage = false;
      if (memberList.size() > 20) {
        hasNextPage = true;
        memberList = memberList.subList(0, 20);
      } else {
        hasNextPage = false;
      }
      for(SmgMember member:memberList){
    	  member.setConstellation(ProjectUtil.date2Constellation(member.getBirthMonth(), member.getBirthDay()));
      }
      resultMap.put("hasNextPage", Boolean.valueOf(hasNextPage));
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
      resultMap.put("memberList", memberList);
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  @RequestMapping({"/listMemberBehavior"})
  @ResponseBody
  public Map<String, Object> listMemberBehavior(@RequestParam String pageNumber,
		  @RequestParam (required=false)Float gpsLongitude,
		  @RequestParam (required=false)Float gpsLatitude
		  )
  {
    Map resultMap = new HashMap();
    try
    {
      SmgMemberBehaviorQuery query = new SmgMemberBehaviorQuery();
      query.setPageNumber(Integer.parseInt(pageNumber));
      setStartAndLimit(query, Integer.parseInt(pageNumber), 20);
      query.setGpsLatitude(gpsLatitude);
      query.setGpsLongitude(gpsLongitude);
      Page behaviorPage = this.smgMemberBehaviorManager.findPage(query);

      resultMap.put("hasNextPage", Boolean.valueOf(behaviorPage.isHasNextPage()));
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
      resultMap.put("behaviorList", behaviorPage.getResult());
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  @RequestMapping({"/listFriendBehavior"})
  @ResponseBody
  public Map<String, Object> listFriendBehavior(@RequestParam String memberId, @RequestParam String pageNumber,
		  @RequestParam (required=false)Float gpsLongitude,
		  @RequestParam (required=false)Float gpsLatitude)
  {
    Map resultMap = new HashMap();
    try
    {
      SmgMemberBehaviorQuery query = new SmgMemberBehaviorQuery();
      query.setPageNumber(Integer.parseInt(pageNumber));
      query.setIsFriend(memberId);
      query.setGpsLatitude(gpsLatitude);
      query.setGpsLongitude(gpsLongitude);
      setStartAndLimit(query, Integer.parseInt(pageNumber), 20);

      Page behaviorPage = this.smgMemberBehaviorManager.findPage(query);

      resultMap.put("hasNextPage", Boolean.valueOf(behaviorPage.isHasNextPage()));
      
      
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
      resultMap.put("behaviorList", behaviorPage.getResult());
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  public void setStartAndLimit(BaseQuery query, int pageNumber, int pageSize) {
		query.setStart((pageNumber-1)* pageSize);
		query.setLimit(  pageSize);
  }

  @RequestMapping({"/listFriend"})
  @ResponseBody
  public Map<String, Object> listFriend(@RequestParam String memberId)
  {
    Map resultMap = new HashMap();
    try {
      SmgMemberQuery query = new SmgMemberQuery();
      
      query.setFriendMemberId(memberId);
      query.setStart(0);
      query.setLimit(100000);
      Page page = this.smgMemberManager.findPage(query);
      List<SmgMember> memberList = page.getResult();
      for(SmgMember member:memberList){
    	  member.setConstellation(ProjectUtil.date2Constellation(member.getBirthMonth(), member.getBirthDay()));
  		}
      resultMap.put("hasNextPage", Boolean.valueOf(page.isHasNextPage()));
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
      resultMap.put("friendList", memberList);
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  @RequestMapping({"/memberinfo"})
  @ResponseBody
  public Map<String, Object> memberInfo(@RequestParam String memberId, @RequestParam(required=false) String fromMemberId)
  {
    Map resultMap = new HashMap();
    try {
      if (StringUtil.isEmpty(memberId)) {
        resultMap.put("state","-2");
        resultMap.put("desc", "用户不存在");
        return resultMap;
      }
      SmgMember member = (SmgMember)this.smgMemberManager.getById(Integer.valueOf(Integer.parseInt(memberId)));
      member.setTakeId(member.getMemberId().intValue() + 10000);
      member.setUnReadMessageCount(5);
      member.setUnReadSystemMessageCount(4);
      if (member.getBirthYear() == 0) {
        member.setAge(25);
      } else {
        int year = Calendar.getInstance().get(1);
        member.setAge(year - member.getBirthYear());
      }
      SmgMemberBehavior behavior = this.smgMemberBehaviorManager.getLastestByMemberId(memberId);
      if (behavior == null)
        member.setLastestBehavior("暂无动态");
      else {
        member.setLastestBehavior(behavior.getCont());
        member.setLastBehaviorId(behavior.getBehaviorId()+"");
      }

      resultMap.put("state", "1");
      if ((fromMemberId != null) && (!(fromMemberId.equals("0")))) {
        SmgMemberFriend smgMemberFriend = this.smgMemberFriendManager.getMemberFriend(Integer.parseInt(fromMemberId), Integer.parseInt(memberId));
        if (smgMemberFriend == null) {
          SmgMemberFocus ff = this.smgMemberFocusManager.getByMemberIdAndFocuseId(Integer.valueOf(Integer.parseInt(fromMemberId)), Integer.valueOf(Integer.parseInt(memberId)));
          if (ff == null)
            member.setIsFocus(0);
          else
            member.setIsFocus(1);

          member.setIsFriend(0);
        } else {
          member.setIsFocus(1);
          member.setIsFriend(1);
        }
      }
      resultMap.put("member", member);
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  @RequestMapping({"/checkin"})
  @ResponseBody
  public Map<String, Object> checkin(@RequestParam String memberId, @RequestParam String nickName, @RequestParam String poiAddress, @RequestParam String memberHeadImage, @RequestParam Float gpsLatitude, @RequestParam Float gpsLongitude)
  {
    Map resultMap = new HashMap();
    try {
      int cityNo = 21;
      SmgPoi poi = this.smgPoiManager.getByCitynoAndAddress(cityNo, poiAddress);
      if (poi == null) {
        poi = new SmgPoi();
        poi.setCityNo(Integer.valueOf(cityNo));
        poi.setPoiAddress(poiAddress);
        poi.setCreateMemberId(Integer.valueOf(Integer.parseInt(memberId)));
        poi.setGpsLatitude(gpsLatitude);
        poi.setGpsLongitude(gpsLongitude);
        this.smgPoiManager.save(poi);
      }
      SmgPoiCheckin checkin = new SmgPoiCheckin();
      checkin.setCityNo(Integer.valueOf(cityNo));
      checkin.setGpsLatitude(gpsLatitude);
      checkin.setGpsLongitude(gpsLongitude);
      checkin.setPoiAddress(poiAddress);
      checkin.setPoiId(poi.getPoiId());
      checkin.setSignupMemberHead(memberHeadImage);
      checkin.setSignupMemberId(Integer.valueOf(Integer.parseInt(memberId)));
      checkin.setSignupMemberName(nickName);
      this.smgPoiCheckinManager.save(checkin);
      resultMap.put("state", "1");
      resultMap.put("desc", "签到成功");
    }
    catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  @RequestMapping({"/listMessageList"})
  @ResponseBody
  public Map<String, Object> unReadMessageList(
		  @RequestParam String memberId, 
		  @RequestParam(required=false)String messageType, 
		  @RequestParam(required=false)String isRead,
		   String pageNumber,
		   String type)
  {
    Map resultMap = new HashMap();
    try {
      SmgMessageQuery query = new SmgMessageQuery();
      query.setFromIsValid(1);
      if (isRead !=null && !(isRead.equals("")))
        query.setIsRead(Integer.valueOf(Integer.parseInt(isRead)));

      if (messageType!=null && !(messageType.equals("")))
        query.setMessageType(Integer.valueOf(Integer.parseInt(messageType)));

      query.setToIsValid(1);
      if (type.equals("1")) {
        query.setFromMemberId(Integer.valueOf(Integer.parseInt(memberId)));
        query.setActionType(Integer.valueOf(0));
      } else {
        query.setToMemberId(Integer.valueOf(Integer.parseInt(memberId)));
      }
      setStartAndLimit(query, Integer.parseInt(pageNumber), 20);
      Page page = this.smgMessageManager.findPage(query);
      resultMap.put("state", "1");
      resultMap.put("desc", "调用成功");
      resultMap.put("pageInfo", page);
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  @RequestMapping({"/queryMember"})
  @ResponseBody
  public Map<String, Object> queryMember(@RequestParam String type, @RequestParam String cont)
  {
    Map resultMap = new HashMap();
    try
    {
      SmgMember member;
      if (type.equals("1"))
        member = this.smgMemberManager.getByLoginName(cont);
      else
        member = this.smgMemberManager.getByNickname(cont);

      if (member == null) {
        resultMap.put("state", "-1");
        resultMap.put("desc", "查找不到用户"); 
        return resultMap;
      }
      resultMap.put("state", "1");
      resultMap.put("desc", "调用成功");
      resultMap.put("memberInfo", member);
    }
    catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  /**
 * @param mobileNumbers
 * @param memberId
 * @return 13813242345:-1 isFriend :-1, notSignUp:-2, signUpNotFriend:  memberId
 */
@RequestMapping({"/isMobileNumberSignup"})
  @ResponseBody
  public Map<String, Object> isMobileNumberSignup(@RequestParam String mobileNumbers,
		  @RequestParam String memberId)
  {
    Map resultMap = new HashMap();
    try {
      String[] arrayOfString1;
      mobileNumbers = mobileNumbers.replaceAll("\\+86", "");
      mobileNumbers = mobileNumbers.replaceAll("#", "");
      List memberList = this.smgMemberManager.getListByMobileNumbers(mobileNumbers);
      Map resultmap = new HashMap();
      
      String[] mobileNumberArray = mobileNumbers.split(",");
      int j = (arrayOfString1 = mobileNumberArray).length;
      for (int i = 0; i < j; ++i) {   
    	String loginName = arrayOfString1[i];
        boolean flag = false;
        SmgMember member = null;
        for (Iterator localIterator = memberList.iterator(); localIterator.hasNext(); ) 
        {
      
          member = (SmgMember)localIterator.next();
          if (loginName.equals(member.getLoginName())) {
        	  flag = true;
            break;
          }
        }

        if ( flag){
        	int isFriend = 0;
        	SmgMemberFriend friend = smgMemberFriendManager.getMemberFriend(Integer.parseInt(memberId),member.getMemberId());
        	if ( friend == null){
        		resultmap.put(loginName, member.getMemberId()+"");
        	}else{
        		resultmap.put(loginName, -1+"");
        	}
        }else{
        	resultmap.put(loginName, -2+"");
        }
      }

      resultMap.put("state", "1");
      resultMap.put("desc", "调用成功");
      resultMap.put("resultmap", resultmap);
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  /**
 * @param request
 * @param memberId
 * @param nickName
 * @param headImage
 * @param cont
 * @param gpsLatitude
 * @param gpsLongitude
 * @return
 * 存  650 和 70  大小的图片
 */
@RequestMapping({"/submitDiary"})
  @ResponseBody
  public Map<String, Object> submitDiary(ServletRequest request,@RequestParam String memberId, 
		  @RequestParam String nickName, @RequestParam String headImage, @RequestParam String cont,
		  @RequestParam(required=false) String address,
		  @RequestParam(required=false) Float gpsLatitude, 
		  
		  @RequestParam(required=false) Float gpsLongitude)
  {
    Map resultMap = new HashMap();
    String image = null;
    String largeImage = null;
    try {
			String path =  ProjectUtil.imageUploadPath;  
			String subfolder = request.getParameter("subfolder");
				//path = "E:\\ddmap\\image\\crm\\";
			if ( subfolder != null && !subfolder.equals("")){
				path = path  + "/" + subfolder;
			}
			path = path +"/";
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
					.getFile("filename");
			long fileSize = file.getSize();
			SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = simpleFormat.format(new Date());
			String imagepath =  path + dateString;
			/*
			File fdir = new File(imagepath);
			if (!fdir.exists()){
				fdir.mkdirs();
			}
			String fileName = file.getFileItem().getName();
			String ext = fileName.substring(fileName.lastIndexOf("."));
			String newFileName = dateString + "-" + System.currentTimeMillis()
					+ ext;
			File f = new File(imagepath + "/" + newFileName);
			FileOutputStream fos = null;
			fos = new FileOutputStream(f);
			fos.write(file.getBytes());
			fos.close();*/ 
			long timestamp = System.currentTimeMillis(); 
			String savepath = FileUtil.uploads(multipartRequest,imagepath,new SimpleDateFormat("HHmmssSSS").format(timestamp),"filename");
			// 判断是否需要缩略图片
			String smallwidthStr = request.getParameter("smallwidth");
			String smallheightStr = request.getParameter("smallheight");
			String extname  = ".png"; 
			CommonsMultipartFile  orginalFile = (CommonsMultipartFile) multipartRequest.getFile("filename");
			ImageUtil2 util = new ImageUtil2();
			FileItem fileItem = orginalFile.getFileItem();
			try {
				int smallwidth = 650;
				int smallheight = 650;
		  		try {
					if(orginalFile != null && !orginalFile.isEmpty()){
					}
		  		}  catch (Exception e){
		  			e.printStackTrace();
		  		}
		  		File f = new File (path + "650/"+dateString+"/");
		  		if (f.exists() == false){
		  			System.out.println(f.mkdirs());
		  		}
			//	util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/650/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, smallwidth, smallheight);
			}catch(Exception e){
				e.printStackTrace();
			}
			
			File f =  new File (path + "120/"+dateString+"/");
	  		if (f.exists() == false){
	  			System.out.println(f.mkdirs());
	  		}
	  	
			// 存1个 100 × 100 的
			util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/120/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, 120, 120);
			//writeMessage(out, savepath.substring(savepath.indexOf("uploadimage/") + 12));
			savepath =  path + "120/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname;
			String imagePrefix = ProjectUtil.imagePrefix;
			image =  imagePrefix + savepath.substring(savepath.indexOf("images/") );
			largeImage = imagePrefix+ ( path +dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname ).substring(
						(path +dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname).indexOf("images/")
					);
		}catch(Exception e){
			e.printStackTrace();
		}
	    try {
	      SmgMemberBehavior behavior = new SmgMemberBehavior();
	      String title = "发表了一篇日志";
	      behavior.setCont(title);
	      behavior.setContPreview(cont);
	      behavior.setHeadImage(headImage);
	      behavior.setImage(image);
	      behavior.setMemberId(Integer.valueOf(Integer.parseInt(memberId)));
	      behavior.setNickName(nickName);
	      behavior.setSourcefrom("mobile");
	      behavior.setTitle(title);
	      behavior.setType(999);
	      behavior.setLargeImage(largeImage);
	      behavior.setGpsLatitude(gpsLatitude==null?0.0f:gpsLatitude.floatValue());
	      behavior.setGpsLongitude(gpsLongitude==null?0.0f:gpsLongitude.floatValue());
	      behavior.setAddress(address==null?"":address);
	      this.smgMemberBehaviorManager.save(behavior);
	      resultMap.put("state", "1");
	      resultMap.put("desc", "调用接口成功");
	    } catch (Exception e) {
	      e.printStackTrace();
	      resultMap.put("state", "-99");
	      resultMap.put("desc", "运行时错误");
	    }
    return resultMap;
  }

  /**
 * @param request
 * @param memberId
 * @param job
 * @param myCars
 * @param likeCars
 * @param signature
 * @param interest
 * @return
 */
	@RequestMapping({"/updateMemberInfo"})
  @ResponseBody
  public Map<String, Object> updateMemberInfo(ServletRequest request,
		  @RequestParam String memberId,
		  @RequestParam(required= false) String job , 
		  @RequestParam(required= false) String myCars, 
		  @RequestParam(required= false) String likeCars,
		  @RequestParam(required= false) String signature,
		  @RequestParam(required= false) String interest,
		  @RequestParam(required= false) String sex)
  {
    Map resultMap = new HashMap();
    String headImage  = null;
    try {
		String path =  ProjectUtil.imageUploadPath;  
		String subfolder = request.getParameter("subfolder");
			//path = "E:\\ddmap\\image\\crm\\";
		if ( subfolder != null && !subfolder.equals("")){
			path = path  + "/" + subfolder;
		}
		path = path +"/";
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		String filename =  "filename";
		// 通过编辑器上传的图片默认的filename
		if ( filename == null ||filename.equals("")){
				filename = "imgFile";
		}
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
				.getFile(filename);
		long fileSize = file.getSize();
		SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = simpleFormat.format(new Date());
		String imagepath =  path + dateString;
		/*
		File fdir = new File(imagepath);
		if (!fdir.exists()){
			fdir.mkdirs();
		}
		String fileName = file.getFileItem().getName();
		String ext = fileName.substring(fileName.lastIndexOf("."));
		String newFileName = dateString + "-" + System.currentTimeMillis()
				+ ext;
		File f = new File(imagepath + "/" + newFileName);
		FileOutputStream fos = null;
		fos = new FileOutputStream(f);
		fos.write(file.getBytes());
		fos.close();*/ 
		long timestamp = System.currentTimeMillis(); 
		String savepath = FileUtil.uploads(multipartRequest,imagepath,new SimpleDateFormat("HHmmssSSS").format(timestamp),filename);
		// 判断是否需要缩略图片
		String extname  = ".png"; 
		CommonsMultipartFile  orginalFile = (CommonsMultipartFile) multipartRequest.getFile(filename);
		System.out.println( "updateMemberInfo orginalFile :"+ orginalFile);
		ImageUtil2 util = new ImageUtil2();
		FileItem fileItem = orginalFile.getFileItem();
		try {
	  		try {
				if(orginalFile != null && !orginalFile.isEmpty()){
				}
	  		}  catch (Exception e){
	  			e.printStackTrace();
	  		}
	  		File f = new File (path + "650/"+dateString+"/");
	  		if (f.exists() == false){
	  			System.out.println(f.mkdirs());
	  		}
		//	util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/650/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, 650, 650);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		File f =  new File (path + "70/"+dateString+"/");
  		if (f.exists() == false){
  			System.out.println(f.mkdirs());
  		}
		// 存1个 100 × 100 的
		util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/70/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, 70, 70);
		//writeMessage(out, savepath.substring(savepath.indexOf("uploadimage/") + 12));
		savepath =  path + "70/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname;
		String imagePrefix = ProjectUtil.imagePrefix;
		headImage =  imagePrefix + savepath.substring(savepath.indexOf("images/") );
		System.out.println( "updateMemberInfo headImage :"+ headImage);
	}catch(Exception e){
		e.printStackTrace();
	}
    try {
      SmgMember smgMember = (SmgMember)this.smgMemberManager.getById(Integer.valueOf(Integer.parseInt(memberId)));
      if (smgMember == null) {
        resultMap.put("state", "-2");
        resultMap.put("desc", "用户不存在"); 
        return resultMap;
      }
      smgMember.setMyCars(myCars);
      smgMember.setLikeCars(likeCars);
      if ( signature != null  && !"".equals(signature )){
    	  smgMember.setSignature(signature);
      }   
      if ( job != null  && !"".equals(job )){
    	  smgMember.setJob(job);
      }
      if ( interest != null  && !"".equals(interest )){
    	  smgMember.setInterest(interest);
      }
      if ( headImage != null ){
    		System.out.println( "updateMemberInfo smgMember.headImage :"+ smgMember.getHeadImage());
    	  smgMember.setHeadImage(headImage);
    	  System.out.println( "updateMemberInfo smgMember.headImage :"+ smgMember.getHeadImage());
      }
      int carBrandId = 0;
      String carBrandIdStr = request.getParameter("carBrandId");
      if ( carBrandIdStr != null ){
    	  smgMember.setCarBrandId(Integer.parseInt(carBrandIdStr));
      }
      String  carBrandName = request.getParameter("carBrandName");
      if ( carBrandName != null ){
    	  smgMember.setCarBrandName(carBrandName);
      }
      String modelIdStr = request.getParameter("modelId");
      if ( modelIdStr != null ){
    	  smgMember.setModelId(Integer.parseInt(modelIdStr));
      }
      String carModelName = request.getParameter("carModelName");
      if ( carModelName != null ){
    	  smgMember.setCarModelName(carModelName);
      }
      String cityAddress = request.getParameter("cityAddress");
      if ( cityAddress != null ){
    	  smgMember.setCityAddress(cityAddress);
      }
      if ( sex != null){
    	  if ( sex.equals("男")){
    		  sex = "m";
    	  }
    	  if ( sex.equals("女")){
    		  sex = "w";
    	  }
    	  smgMember.setSex(sex);
      }
      //    1-车主 2-车友
      String memberCarType = request.getParameter("memberCarType");
      if ( memberCarType !=null && !"".equals("memberCarType")){
    	  smgMember.setMemberCarType(Integer.parseInt(memberCarType));
      }
      String birthDay = request.getParameter("birthDay");
      if ( birthDay == null){
    	  birthDay = request.getParameter("birthday");
      }
      if ( birthDay !=null){
    	  try{
    		  String[] temp = birthDay.split("-");
    		  smgMember.setBirthYear(Integer.parseInt(temp[0]));
    		  smgMember.setBirthMonth(Integer.parseInt(temp[1]));
    		  smgMember.setBirthDay(Integer.parseInt(temp[2]));
    	  }catch(Exception e){
    		  e.printStackTrace();
    	  }
      }
      this.smgMemberManager.update(smgMember);
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
      resultMap.put("member",smgMember);
    }
    catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  @RequestMapping({"/behaviorInfo"})
  @ResponseBody
  public Map<String, Object> behaviorInfo(@RequestParam String behaviorId, @RequestParam String pageNumber,
		  @RequestParam(required=false) String memberId)
  {
    Map resultMap = new HashMap();
    try {
      SmgMemberBehavior behavior = (SmgMemberBehavior)this.smgMemberBehaviorManager.getById(Integer.valueOf(Integer.parseInt(behaviorId)));
      if (behavior != null) {
        resultMap.put("state", "1");
        resultMap.put("desc", "调用接口成功");
        resultMap.put("behavior", behavior);
        SmgMemberBehaviorCommentQuery query = new SmgMemberBehaviorCommentQuery();
        query.setFkBehaviorId(Integer.valueOf(Integer.parseInt(behaviorId)));
        setStartAndLimit(query, Integer.parseInt(pageNumber), 25);
        Page page = this.smgMemberBehaviorCommentManager.findPage(query);
        //0 true
//        1false

        int canPraise = 0;
        if ( memberId != null){
        	SmgMemberBehaviorComment comment = smgMemberBehaviorCommentManager.getByMemberIdAndBehaviorId(memberId,behaviorId);
        	if ( comment != null){
        		canPraise = 1;
        	}
        }
        resultMap.put("canPraise", canPraise);
        resultMap.put("commentPage", page);
      }else{
    	  resultMap.put("state", "-2");
    	  resultMap.put("desc", "动态不存在");
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    label189: return resultMap;
  }

  /**
 * @param memberId
 * @param nickName
 * @param headImage
 * @param behaviorId
 * @param cont
 * @param commentType
 * @return
 */
@RequestMapping({"/praiseBehavior"})
  @ResponseBody
  public Map<String, Object> praiseBehavior(@RequestParam String memberId, @RequestParam String nickName, @RequestParam String headImage, @RequestParam String behaviorId, @RequestParam String cont, @RequestParam String commentType)
  {
    Map resultMap = new HashMap();
    try {
      SmgMemberBehaviorComment comment = new SmgMemberBehaviorComment();
      comment.setCommentType(Integer.valueOf(Integer.parseInt(commentType)));
      if (commentType.equals("2"))
        comment.setCont(nickName + " 觉得很赞!");
      else
        comment.setCont(cont);

      comment.setFkBehaviorId(Integer.valueOf(behaviorId));
      comment.setHeadImage(headImage);
      comment.setMemberId(Integer.valueOf(Integer.parseInt(memberId)));
      comment.setNickName(nickName);
      this.smgMemberBehaviorCommentManager.save(comment);
      smgMemberBehaviorCommentManager.updateCountByType(behaviorId,commentType);
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
      //int totalCount = smgMemberBehaviorCommentManager.getCountByType(behaviorId,commentType);
      //resultMap.put("totalCount", totalCount+"");
      int praiseCount = smgMemberBehaviorCommentManager.getCountByType(behaviorId,"2");
      resultMap.put("praiseCount", praiseCount+"");
      int commentCount = smgMemberBehaviorCommentManager.getCountByType(behaviorId,"1");
      resultMap.put("commentCount", commentCount+"");
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

	 /** 
     * 获取汉字串拼音首字母，英文字符不变 
     * 
     * @param chinese 汉字串 
     * @return 汉语拼音首字母 
     */ 
    public static String cn2FirstSpell(String chinese) {
    		if ( StringUtil.isEmpty(chinese)){
    			return "";
    		}
    		String firstString = chinese.substring(0,1);
    		firstString = firstString.toLowerCase();
    		System.out.println ( "firstString  = " +firstString );
    		String englishOrNumberStr = "0123456789abcdefghijklmnopqrstuvwxyz";
    		try{
    			if (  englishOrNumberStr.indexOf(firstString) != -1){
    				return  firstString.toUpperCase();
    			}
    		}catch(Exception e){
    			
    		}
    		if ( !isChinese(firstString)){
    			return firstString;
    		}
            StringBuffer pybf = new StringBuffer(); 
            char[] arr = chinese.toCharArray(); 
            HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); 
            defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); 
            defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); 
            for (int i = 0; i < arr.length; i++) { 
                    if (arr[i] > 128) { 
                            try { 
                                    String[] _t = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat); 
                                    if (_t != null) { 
                                            pybf.append(_t[0].charAt(0)); 
                                    } 
                            } catch (BadHanyuPinyinOutputFormatCombination e) { 
                                    e.printStackTrace(); 
                            } 
                    } else { 
                            pybf.append(arr[i]); 
                    } 
            } 
            return pybf.toString().replaceAll("\\W", "").trim().toUpperCase().substring(0,1); 
    } 

  @RequestMapping({"/addFriend"})
  @ResponseBody
  public Map<String, Object> addFriend(@RequestParam String fromMemberId, @RequestParam String toMemberId)
  {
    Map resultMap = new HashMap();
    try {
      SmgMember fromMember = (SmgMember)this.smgMemberManager.getById(Integer.valueOf(Integer.parseInt(fromMemberId)));
      SmgMember toMember = (SmgMember)this.smgMemberManager.getById(Integer.valueOf(Integer.parseInt(toMemberId)));
      SmgMessage message = null;
      boolean saveMessage = false;
      try {
	      message = smgMessageManager.getUndealAddFriendMessage(fromMember.getMemberId(),toMember.getMemberId());
	      if ( message != null ){
	    	  resultMap.put("state", "1");
	          resultMap.put("desc", "已经发送过好友请求");
	    //      return resultMap;
	      }else{
	    	  saveMessage = true;
	      }
      }catch(Exception e){
    	  e.printStackTrace();
    	  return resultMap;
      }
    //判断是否已经有此消息
      message = new SmgMessage();
      message.setActionType(1);
      message.setFromMemberHeadImage(fromMember.getHeadImage());
      message.setFromMemberId(fromMember.getMemberId());
      message.setFromMemberNickName(fromMember.getNickName());
      message.setMessageCont(fromMember.getNickName() + "请求添加你为好友.");
      message.setMessageTitle(fromMember.getNickName() + "请求添加你为好友.");
      message.setMessageType(Integer.valueOf(2));
      message.setToMemberHeadImage(toMember.getHeadImage());
      message.setToMemberId(toMember.getMemberId());
      message.setToMemberNickName(toMember.getNickName());
      if ( saveMessage){
    	  this.smgMessageManager.save(message);
      }
      Gson gson = new Gson();
	  	TalkHistory talkHistory =  new TalkHistory();
	  	talkHistory.setContent(message.getMessageCont());
	  	talkHistory.setFromId(fromMember.getMemberId()+"");
	  	talkHistory.setTargetId(toMember.getMemberId()+"");
	  	talkHistory.setTargetType(3+"");
	  	// yyyy年MM月dd日 HH:mm:ss
	  	SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss") ;
	  	String date = df.format(new Date());
	  	talkHistory.setDate(date);
		// TODO 保存到数据库中
		// TODO 把数据库主键塞回到talkHistory.setServerSideId
		// TODO 再把这个对象解析成json返回给我,并且返回发送成功与否
	  	String uuid = memberIdDeviceIdMap.get(toMember.getMemberId());
	  	if ( uuid == null){
	  		uuid =  toMember.getUuid();
	  		memberIdDeviceIdMap.put(toMember.getMemberId()+"", uuid);
	  	}
	  	if ( uuid != null){
	  		uuid = uuid.replaceAll("-", "");
	  	}
		 System.out.println(" in addFriend");
		 smgTalkHistoryManager.save(talkHistory);
		MessageResult messageResult = talkService.sendmsg(uuid,
			talkHistory.getTargetId(), "", gson.toJson(talkHistory));
	 System.out.println("addFriend uuid :"+uuid+" targetId:"+talkHistory.getTargetId()+" messageResult:"+messageResult+" talkHistory.getServerSideId :"+talkHistory.getServerSideId());
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state","-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }

  @RequestMapping({"/dealAddfrindMessage"})
  @ResponseBody
  public Map<String, Object> dealAddfrindMessage(@RequestParam String mid, @RequestParam String result)
  {
    Map resultMap = new HashMap();
    try {
      SmgMessage message = (SmgMessage)this.smgMessageManager.getById(Integer.valueOf(Integer.parseInt(mid)));
      SmgMember fromMember = (SmgMember)this.smgMemberManager.getById(message.getFromMemberId());
      SmgMember toMember = (SmgMember)this.smgMemberManager.getById(message.getToMemberId());
      String toMemberNickName = toMember.getNickName();
      String fromMemberNickName = fromMember.getNickName();
      message.setIsRead(1);
      message.setIsDeal(1);
      if (result.equals("1"))
        message.setActionResult(toMemberNickName + "通过了你的好友请求");
      else if (result.equals("0"))
        message.setActionResult(toMemberNickName + "拒绝了你的好友请求");

      this.smgMessageManager.update(message);
      SmgMessage newMessage = new SmgMessage();
      newMessage.setActionType(1);
      newMessage.setFromMemberHeadImage(toMember.getHeadImage());
      newMessage.setFromMemberId(toMember.getMemberId());
      newMessage.setFromMemberNickName(toMember.getNickName());
      if (result.equals("1")) {
        newMessage.setMessageCont(toMemberNickName + "通过了你的好友请求");
        newMessage.setMessageTitle(toMember.getNickName() + "通过了你的好友请求");
        SmgMemberFriend friend = new SmgMemberFriend();
        friend.setMemberIdA(fromMember.getMemberId());
        friend.setMemberIdB(toMember.getMemberId());
        this.smgMemberFriendManager.save(friend);
        SmgMemberFocus focus = new SmgMemberFocus();
        if (this.smgMemberFocusManager.getByMemberIdAndFocuseId(fromMember.getMemberId(), toMember.getMemberId()) == null) {
          focus.setFromMemberId(fromMember.getMemberId());
          focus.setFocusMemberId(toMember.getMemberId());
          this.smgMemberFocusManager.save(focus);
        }

        if (this.smgMemberFocusManager.getByMemberIdAndFocuseId(toMember.getMemberId(), fromMember.getMemberId()) == null) {
          focus.setFromMemberId(toMember.getMemberId());
          focus.setFocusMemberId(fromMember.getMemberId());
          this.smgMemberFocusManager.save(focus);
        }
      } else if (result.equals("0")) {
        newMessage.setMessageCont(toMemberNickName + "拒绝了你的好友请求");
        newMessage.setMessageTitle(toMember.getNickName() + "拒绝了你的好友请求");
      }

      newMessage.setMessageType(1);
      newMessage.setToMemberHeadImage(fromMember.getHeadImage());
      newMessage.setToMemberId(fromMember.getMemberId());
      newMessage.setToMemberNickName(fromMember.getNickName());
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
        Gson gson = new Gson();
	  	TalkHistory talkHistory =  new TalkHistory();
	  	talkHistory.setContent(newMessage.getMessageCont());
	  	talkHistory.setFromId(toMember.getMemberId()+"");
	  	talkHistory.setTargetId(fromMember.getMemberId()+"");
	  	talkHistory.setTargetType(2+"");
	  	// yyyy年MM月dd日 HH:mm:ss
	  	SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss") ;
	  	String date = df.format(new Date());
	  	talkHistory.setDate(date);
		// TODO 保存到数据库中
		// TODO 把数据库主键塞回到talkHistory.setServerSideId
		// TODO 再把这个对象解析成json返回给我,并且返回发送成功与否
	  	String uuid = memberIdDeviceIdMap.get(fromMember.getMemberId());
	  	if ( uuid == null){
	  		uuid =  fromMember.getUuid();
	  		memberIdDeviceIdMap.put(fromMember.getMemberId()+"", uuid);
	  	}
	  	if ( uuid != null){
	  		uuid = uuid.replaceAll("-", "");
	  	}
		MessageResult messageResult = talkService.sendmsg(uuid,
			talkHistory.getTargetId(), "", gson.toJson(talkHistory));
	   System.out.println("dealAddFriendMessage messageResult  talkHistory :"+ gson.toJson(talkHistory) +"  :  " +messageResult.getErrcode() +  ":"+messageResult.getErrmsg());
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }
  @RequestMapping({"/uploadimage"})
  @ResponseBody
  public  void  uploadImage( //@RequestParam byte[] imageByte
		  ServletRequest request,HttpServletResponse response) throws IOException
  {
	  response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		Writer out = response.getWriter();
		String path =  "D:\\nginx-1.4.1\\root\\images";
		String subfolder = request.getParameter("subfolder");
			//path = "E:\\ddmap\\image\\crm\\";
		if ( subfolder != null && !subfolder.equals("")){
			path = path  + "/" + subfolder;
		}
		path = path +"/";
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		String filename =  "filename";
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
				.getFile("filename");
		long fileSize = file.getSize();
		String maxSize = request.getParameter("maxsize");
		if(maxSize !=null ){
			float max = Float.parseFloat(maxSize)*1024*1024;
			if(fileSize >   max){
				return ;
			}
		}
		SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = simpleFormat.format(new Date());
		String imagepath =  path + dateString;
		/*
		File fdir = new File(imagepath);
		if (!fdir.exists()){
			fdir.mkdirs();
		}
		String fileName = file.getFileItem().getName();
		String ext = fileName.substring(fileName.lastIndexOf("."));
		String newFileName = dateString + "-" + System.currentTimeMillis()
				+ ext;
		File f = new File(imagepath + "/" + newFileName);
		FileOutputStream fos = null;
		fos = new FileOutputStream(f);
		fos.write(file.getBytes());
		fos.close();*/ 
		long timestamp = System.currentTimeMillis(); 
		String savepath = FileUtil.uploads(multipartRequest,imagepath,new SimpleDateFormat("HHmmssSSS").format(timestamp),filename);
		// 判断是否需要缩略图片
		String smallwidthStr = request.getParameter("smallwidth");
		String smallheightStr = request.getParameter("smallheight");
		String extname  = ""; 
		if ( filename.equals("imgFile")){
			smallwidthStr = "650";
			smallheightStr = "650";
		}
		ImageUtil2 util = new ImageUtil2();
		if ( smallwidthStr!=null && !smallwidthStr.equals("") && smallheightStr!=null && !"".equals(smallheightStr)){
			try {
				int smallwidth = Integer.parseInt(smallwidthStr);
				int smallheight = Integer.parseInt(smallheightStr); 
				CommonsMultipartFile  orginalFile = (CommonsMultipartFile) multipartRequest.getFile(filename);
		  		try {
					if(orginalFile != null && !orginalFile.isEmpty()){
							FileItem fileItem = orginalFile.getFileItem();
				  			extname = fileItem.getName().substring(fileItem.getName().lastIndexOf("."));
					}
		  		}  catch (Exception e){
		  			e.printStackTrace();
		  		}
		  		File f = new File (path + "650/"+dateString+"/");
		  		if (f.exists() == false){
		  			System.out.println(f.mkdirs());
		  		}
			//	util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/650/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, smallwidth, smallheight);
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
		File f = new File (path + "70/"+dateString+"/");
		if (f.exists() == false){
			System.out.println(f.mkdirs());
		}try {
			util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/70/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, 70, 70);
		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println(savepath);
		if ( smallwidthStr!=null && !smallwidthStr.equals("") && smallheightStr!=null && !"".equals(smallheightStr)){
			savepath =  path + "70/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname;
		}else{
		}
		Map<String,Object> param = new HashMap<String,Object>();
		Gson gson = new Gson();
		param.put("error", 0);
		String imagePrefix = "http://121.199.4.98:8888/";
		param.put("url", imagePrefix + savepath.substring(savepath.indexOf("images/") ));
		try {
			out.write( gson.toJson(param));
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
  }  
  /**
 * @param memberId 用户Id
 * @param mids    消息id序列 
 * @return
 */
@RequestMapping({"/deleteRecevieMessage"})
  @ResponseBody
  public Map<String, Object> deleteRecevieMessage(@RequestParam String memberId, @RequestParam String mids)
  {
    Map resultMap = new HashMap();
    try {
     smgMessageManager.deleteReceiveMessage(memberId,mids);
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return resultMap;
  }
  

@RequestMapping({"/checkVersion"})
@ResponseBody
public Map<String, Object> checkVersion(@RequestParam String versionCode)
{
  Map resultMap = new HashMap();
  try {
	boolean hasNewVersion  = false;
	SmgAndroidVersion version = smgAndroidVersionManager.getByVersionCode(versionCode);
	if ( version != null){
		SmgAndroidVersion newVersion   = smgAndroidVersionManager.getNewVersion(version.getId());
		if ( newVersion != null){
			hasNewVersion = true;
			resultMap.put("newVersion",newVersion);
		}
	}
    resultMap.put("hasNewVersion",hasNewVersion);
    resultMap.put("state", "1");
    resultMap.put("desc", "调用接口成功");
  } catch (Exception e) {
    e.printStackTrace();
    resultMap.put("state", "-99");
    resultMap.put("desc", "运行时错误");
  }
  return resultMap;
}

@RequestMapping({"/getCarBrand"})
@ResponseBody
public Map<String, Object> getCarBrand()
{
  Map resultMap = new HashMap();
  List<SmgCarBrand> list  = smgCarBrandManager.getAllBrand();
  for ( SmgCarBrand  carBrand: list){
	 List<SmgCarModels> s = smgCarModelsManager.getByBrandId(carBrand.getCarBrandId());
	 if ( s!= null){
		 carBrand.setModelList(s);
	 }
  }
  try {
    resultMap.put("state", "1");
    resultMap.put("brandList", list);
    resultMap.put("desc", "调用接口成功");
  } catch (Exception e) {
    e.printStackTrace();
    resultMap.put("state", "-99");
    resultMap.put("desc", "运行时错误");
  }
  return resultMap;
}

/**
 * @param timestamp    时间戳  用来校验验证码
 * @param mobileNumber  手机号码
 * @return   成功 {"state":"1","desc":"验证码已发送"}  失败 {"state":"-1","desc":"手机号码已经被注册"}
 */
@RequestMapping({"/sendRegVerifycode"})
@ResponseBody
public Map<String, Object> sendRegVerifycode(@RequestParam String timestamp, @RequestParam String mobileNumber)
{
  Map resultMap = new HashMap();
  try {
	 if ( !ProjectUtil.isMobileNO(mobileNumber) ){
		  resultMap.put("state", "-1");
		  resultMap.put("desc", "手机号码格式不正确");
		 return resultMap;
	 }
	 try {
		 SmgMember member = smgMemberManager.getByLoginName(mobileNumber);
		 if ( member != null ){
			 resultMap.put("state", "-2");
		 	 resultMap.put("desc", "手机号码已经被注册");
		 	 return resultMap;
		 }
	 }catch(Exception e){
		 e.printStackTrace();
		 resultMap.put("state", "-2");
		 resultMap.put("desc", "手机号码已经被注册");
		 return resultMap;
	 }
	 
	String verifyCode =( System.currentTimeMillis()+"").substring(7,13);  
	String message = "欢迎注册踏客社区,您的验证码为" +verifyCode+" ,请在注册页面输入以完成注册.";
	SmgRegVerifycodeRecord record = new  SmgRegVerifycodeRecord();
	record.setMobileNumber(mobileNumber);
	record.setTimestamp(timestamp);
	record.setVerifycode(verifyCode);
	smgRegVerifycodeRecordManager.save(record);
	sendSms(mobileNumber,message);
    resultMap.put("state", "1");
    resultMap.put("desc", "验证码已发送");
  } catch (Exception e) {
    e.printStackTrace();
    resultMap.put("state", "-99");
    resultMap.put("desc", "运行时错误");
   
  }
  return resultMap;
}
/**
 * 第二个版本的注册
 * @param nickName  --  昵称
 * @param loginName --  登录的手机号
 * @param password  --  密码
 * @param verifyCode -- 验证码 这个验证码是用户输入的 我们下发的
 * @param appSource
 * @param appVersion
 * @param regSource
 * @Papar timestamp  -- 获取验证码时保存的timestamp
 * @return
 */
@RequestMapping({"/v2/reg"})
@ResponseBody
public Map<String, Object> V2reg(@RequestParam String nickName,@RequestParam String timestamp,
		@RequestParam String loginName, @RequestParam String password, @RequestParam String verifyCode, 
		@RequestParam String appSource, @RequestParam String appVersion, @RequestParam String regSource,
		@RequestParam String uuid,HttpServletRequest request)
{
	String headImage = null;
	 try {
			String path =  ProjectUtil.imageUploadPath;  
			String subfolder = request.getParameter("subfolder");
				//path = "E:\\ddmap\\image\\crm\\";
			if ( subfolder != null && !subfolder.equals("")){
				path = path  + "/" + subfolder;
			}
			path = path +"/";
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			String filename =  "filename";
			// 通过编辑器上传的图片默认的filename
			if ( filename == null ||filename.equals("")){
					filename = "imgFile";
			}
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
					.getFile(filename);
			long fileSize = file.getSize();
			SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
			String dateString = simpleFormat.format(new Date());
			String imagepath =  path + dateString;
			/*
			File fdir = new File(imagepath);
			if (!fdir.exists()){
				fdir.mkdirs();
			}
			String fileName = file.getFileItem().getName();
			String ext = fileName.substring(fileName.lastIndexOf("."));
			String newFileName = dateString + "-" + System.currentTimeMillis()
					+ ext;
			File f = new File(imagepath + "/" + newFileName);
			FileOutputStream fos = null;
			fos = new FileOutputStream(f);
			fos.write(file.getBytes());
			fos.close();*/ 
			long timestamp2 = System.currentTimeMillis(); 
			String savepath = FileUtil.uploads(multipartRequest,imagepath,new SimpleDateFormat("HHmmssSSS").format(timestamp2),filename);
			// 判断是否需要缩略图片
			String extname  = ".png"; 
			CommonsMultipartFile  orginalFile = (CommonsMultipartFile) multipartRequest.getFile(filename);
			System.out.println( "updateMemberInfo orginalFile :"+ orginalFile);
			ImageUtil2 util = new ImageUtil2();
			FileItem fileItem = orginalFile.getFileItem();
			try {
		  		try {
					if(orginalFile != null && !orginalFile.isEmpty()){
					}
		  		}  catch (Exception e){
		  			e.printStackTrace();
		  		}
		  		File f = new File (path + "650/"+dateString+"/");
		  		if (f.exists() == false){
		  			System.out.println(f.mkdirs());
		  		}
			//	util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname,path + "/650/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp)+extname, 650, 650);
			}catch(Exception e){
				e.printStackTrace();
			}
			
			File f =  new File (path + "70/"+dateString+"/");
	  		if (f.exists() == false){
	  			System.out.println(f.mkdirs());
	  		}
			// 存1个 100 × 100 的
			util.saveImageAsJpg(imagepath+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp2)+extname,path + "/70/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp2)+extname, 70, 70);
			//writeMessage(out, savepath.substring(savepath.indexOf("uploadimage/") + 12));
			savepath =  path + "70/"+dateString+"/"+new SimpleDateFormat("HHmmssSSS").format(timestamp2)+extname;
			String imagePrefix = ProjectUtil.imagePrefix;
			headImage =  imagePrefix + savepath.substring(savepath.indexOf("images/") );
			System.out.println( "updateMemberInfo headImage :"+ headImage);
		}catch(Exception e){
			e.printStackTrace();
		}
	/** 
	 * 校验验证码
	 */
	  Map map = new HashMap();
  try {
	SmgRegVerifycodeRecord record =   smgRegVerifycodeRecordManager.getByVerifyCodeAndTimeStampAndMobileNumber(verifyCode,timestamp,loginName);
  	if (record == null ){
  		 map.put("state", "-1");
  	      map.put("desc", "验证码验证失败");
  	      return map;
  	}
  }catch(Exception e){
	  map.put("state", "-1");
      map.put("desc", "验证码验证失败");
	  e.printStackTrace();
	  return map;
  }

  Map paramMap = new HashMap();
  int type = ProjectUtil.getRegTargetType(loginName);
  if (type == Constant.INVALID_LOGINNAME) {
  }
  paramMap.put("target", loginName);
  paramMap.put("type", ProjectUtil.getRegTargetType(loginName));
  paramMap.put("nickName", nickName);
  paramMap.put("passwd", password);
  Gson gson = new Gson();
  String param = gson.toJson(paramMap);
  String addMemberUrl = REG_LOGIN_SEVICE_URL + "/account/addAccountV2.action?param=" + param;
  this.logger.debug(addMemberUrl);
  String addMemberResult = HttpRequestProxy.doGet(addMemberUrl, "UTF-8");
  if (addMemberResult == null) {
    map.put("state", "-1");
    map.put("desc", "注册失败");
  } else {
    Map addMemberMap = GsonUtil.getMapByJsonString(addMemberResult);
    if (((String)addMemberMap.get("resultCode")).equals("0"))
    {
      SmgMember member = new SmgMember();
      member.setAppSource(appSource);
      member.setAppVersion(appVersion);
      if (type == 2) {
        member.setEmail(loginName);
        member.setIsEmailVerify(1);
        member.setIsMobileVerify(Integer.valueOf(0));
      } else if (type == 1) {
        member.setMobileNumber(loginName);
        member.setIsMobileVerify(1);
        member.setIsEmailVerify(Integer.valueOf(0));
      }
      member.setHeadImage(headImage);

      member.setLastLoginDate(new Date());
      member.setLoginName(loginName);
      member.setNickName(nickName);
      member.setPassword(StringUtil.getMD5Str(password));
      member.setRegDate(new Date());
      member.setRegSource(regSource);
      member.setSex("m");
      member.setSignature("");
      member.setThirdPartyToken(null);
      member.setTopicCount(Integer.valueOf(0));
      member.setIsNewMember(1);
      member.setNickNameFirstChar(cn2FirstSpell(nickName));
      member.setUuid(uuid);
      uuid = uuid.replaceAll("-","");
      memberIdDeviceIdMap.put(member.getMemberId()+"",uuid);
      try
      {
        this.smgMemberManager.save(member);
      } catch (Exception e) {
        e.printStackTrace();
      }
      map.put("member", member);
      map.put("state", "1");
      map.put("desc", "调用接口成功");
    }
    else {
      map.put("state","-2");
      map.put("desc", addMemberMap.get("resultMsg"));
    }
  }
  return map;
}
	/**
	 * 提交意见
	 * @param memberId 用户Id
	 * @param content  内容
	 * @param appVersion 版本号
	 * @param appSource 来源  安卓或者ios
	 * @return
	 */
	@RequestMapping({"/addSuggestion"})
	@ResponseBody
	public Map<String, Object> addSuggestion(@RequestParam String memberId, @RequestParam String content,@RequestParam String appVersion,@RequestParam String appSource)
	{
	  Map resultMap = new HashMap();
	  SmgAppSuggestion smgAppSuggestion = new  SmgAppSuggestion();
	  try { 
	    resultMap.put("state", "1");
	    smgAppSuggestion.setMemberId(Integer.parseInt(memberId));
	    smgAppSuggestion.setAppVersion(appVersion);
	    smgAppSuggestion.setAppSource(appSource);
	    smgAppSuggestion.setContent(content);
	    smgAppSuggestionManager.save(smgAppSuggestion);
	    resultMap.put("desc", "调用接口成功");
	  } catch (Exception e) {
	    e.printStackTrace();
	    resultMap.put("state", "-99");
	    resultMap.put("desc", "运行时错误");
	  }
	  return resultMap;
	}
	 /**
	  * 取消关注
	 * @param fromMemberId  取消动作的发起者
	 * @param toMemberId    取消对谁的关注
	 * @return
	 */
	@RequestMapping({"/cancleFocus"})
	  @ResponseBody
	  public Map<String, Object> cancleFocus(@RequestParam String fromMemberId, @RequestParam String toMemberId)
	  {
	    Map resultMap = new HashMap();
	    try {
	      resultMap.put("state", "1");
	      resultMap.put("desc", "调用接口成功");
	      smgMemberFocusManager.deleteByFromMemberIdAndFocusMemberId(Integer.parseInt(fromMemberId), Integer.parseInt(toMemberId));
	    } catch (Exception e) {
	      e.printStackTrace();
	      resultMap.put("state", "-99");
	      resultMap.put("desc", "运行时错误");
	    }
	    return resultMap;
	  }

	/**
	 * 举报用户
	 * @param fromMemberId 举报者
	 * @param toMemberId   被举报者
	 * @return
	 */
	@RequestMapping({"/reportMember"})
	@ResponseBody
	public Map<String, Object> reportMember(@RequestParam String fromMemberId, @RequestParam String toMemberId,
			@RequestParam(required=false)  String reason)
	{
		SmgMemberReport r = smgMemberReportManager.getByFromMemberIdAndToMemberId(fromMemberId,toMemberId);
		Map resultMap = new HashMap();
		if ( r != null){
			resultMap.put("state", "1");
			resultMap.put("desc", "您已举报过该用户");
			return resultMap;
		}
		r = new SmgMemberReport();
		r.setFromMemberId(Integer.parseInt(fromMemberId));
		r.setToMemberId(Integer.parseInt(toMemberId));
		r.setReason(reason)	;	
		smgMemberReportManager.save(r);
		try {
			resultMap.put("state", "1");
			resultMap.put("desc", "调用接口成功");
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("state", "-99");
			resultMap.put("desc", "运行时错误");
		}
		return resultMap;
	}
	
	
	@RequestMapping({"/sendmessage"})
	@ResponseBody
	public Map<String, Object> sendmessage(@RequestParam String fromId,@RequestParam String targetId, @RequestParam String cont)
	{
	Map resultMap = new HashMap();
	try {

		  Gson gson = new Gson();
		  	TalkHistory talkHistory =  new TalkHistory();
		  	talkHistory.setContent(cont);
		  	talkHistory.setFromId(fromId);
		  	talkHistory.setTargetId(targetId);
		  	talkHistory.setTargetType(0+"");
		  	talkHistory.setTitle(cont);
		  	// yyyy年MM月dd日 HH:mm:ss
		  	SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss") ;
		  	String date = df.format(new Date());
		  	talkHistory.setDate(date);
		  	smgTalkHistoryManager.save(talkHistory);  
			// TODO 保存到数据库中
			// TODO 把数据库主键塞回到talkHistory.setServerSideId
			// TODO 再把这个对象解析成json返回给我,并且返回发送成功与否
		  	String uuid = memberIdDeviceIdMap.get(targetId+"");
		  	if ( uuid == null){
		  		SmgMember member = smgMemberManager.getById(Integer.parseInt(targetId));
		  		uuid = member.getUuid();
		  		memberIdDeviceIdMap.put(targetId,uuid);
		  	}
		  	if ( uuid != null){
		  		uuid = uuid.replaceAll("-", "");
		  	}
			MessageResult messageResult = talkService.sendmsg(uuid,
				talkHistory.getTargetId(), "", gson.toJson(talkHistory));
			System.out.println( gson.toJson(messageResult));
	  resultMap.put("state", "1");
	  resultMap.put("desc", "调用接口成功");
	  resultMap.put("uuid", uuid);
	  resultMap.put("messageResult", messageResult);
	  resultMap.put("talkHistory", talkHistory);
	} catch (Exception e) {
	  e.printStackTrace();
	  resultMap.put("state", "-99");
	  resultMap.put("desc", "运行时错误");
	}
	return resultMap;
	}
	@RequestMapping({"/sendmessage2"})
	@ResponseBody
	public Map<String, Object> sendmessage2(@RequestParam String fromId,@RequestParam String targetId, @RequestParam String cont)
	{
	Map resultMap = new HashMap();
	try {

		  Gson gson = new Gson();
		  	TalkHistory talkHistory =  new TalkHistory();
		  	talkHistory.setContent(cont);
		  	talkHistory.setFromId(fromId);
		  	talkHistory.setTargetId(targetId);
		  	talkHistory.setTargetType(2+"");
		  	talkHistory.setTitle(cont);
		  	// yyyy年MM月dd日 HH:mm:ss
		  	SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss") ;
		  	String date = df.format(new Date());
		  	talkHistory.setDate(date);
		  	smgTalkHistoryManager.save(talkHistory);  
			// TODO 保存到数据库中
			// TODO 把数据库主键塞回到talkHistory.setServerSideId
			// TODO 再把这个对象解析成json返回给我,并且返回发送成功与否
		  	String uuid = memberIdDeviceIdMap.get(targetId+"");
		  	if ( uuid == null){
		  		SmgMember member = smgMemberManager.getById(Integer.parseInt(targetId));
		  		uuid = member.getUuid();
		  		memberIdDeviceIdMap.put(targetId,uuid);
		  	}
		  	if ( uuid != null){
		  		uuid = uuid.replaceAll("-", "");
		  	}
			MessageResult messageResult = talkService.sendmsg(uuid,
				talkHistory.getTargetId(), "", gson.toJson(talkHistory));
			System.out.println( "messageResult :"+gson.toJson(messageResult));
	  resultMap.put("state", "1");
	  resultMap.put("desc", "调用接口成功");
	  resultMap.put("uuid", uuid);
	  resultMap.put("messageResult", messageResult);
	  resultMap.put("talkHistory", talkHistory);
	} catch (Exception e) {
	  e.printStackTrace();
	  resultMap.put("state", "-99");
	  resultMap.put("desc", "运行时错误");
	}
	return resultMap;
	}
	 @RequestMapping({"/getuuid"})
	  @ResponseBody
	  public Map<String, Object> getuuid(@RequestParam String memberId)
	  {
	    Map resultMap = new HashMap();
	    try {
	      SmgMember member = smgMemberManager.getById(Integer.parseInt(memberId));
	      resultMap.put("uuidInMap", memberIdDeviceIdMap.get(memberId));
	      resultMap.put("uuidInDataBase",member.getUuid());
	      resultMap.put("state", "1");
	      resultMap.put("desc", "调用接口成功");
	    } catch (Exception e) {
	      e.printStackTrace();
	      resultMap.put("state", "-99");
	      resultMap.put("desc", "运行时错误");
	    }
	    return resultMap;
	  }
	 @RequestMapping({"/getLatestApk"})
	  public void getLatestApk(HttpServletResponse response) throws IOException
	  {
		 Map resultMap = new HashMap();
		 boolean hasNewVersion  = false;
		 SmgAndroidVersion newVersion   = smgAndroidVersionManager.getLatestVersion();
		 if ( newVersion!=null){
			 response.sendRedirect(newVersion.getDownloadUrl());
		 }
	  }
	 

	@RequestMapping({"/startthread"})
	  @ResponseBody
	  public Map<String, Object> startthread()
	  {
	    Map resultMap = new HashMap();
	    try {
	    	 new SaveNearByMajiaThread(smgMemberManager, smgMemberCoorManager).start();	
	      resultMap.put("state", "1");
	      resultMap.put("desc", "调用接口成功");
	    } catch (Exception e) {
	      e.printStackTrace();
	      resultMap.put("state", "-99");
	      resultMap.put("desc", "运行时错误");
	    }
	    return resultMap;
	  }
	@RequestMapping({"/getFindPasswordVerifyCode"})
	  @ResponseBody
	  public Map<String, Object> getFindPasswordVerifyCode(  @RequestParam String loginName, @RequestParam String timestamp)
	  {
		  Map resultMap = new HashMap();
		  try {
			 if ( !ProjectUtil.isMobileNO(loginName) ){
				  resultMap.put("state", "-1");
				  resultMap.put("desc", "手机号码格式不正确");
				  return resultMap;
			 }
			    
		    String newpwd = StringUtil.getMD5Str(pwd + timestamp);
		    this.logger.debug(newpwd);
		    newpwd = newpwd.toUpperCase();
		    this.logger.debug(newpwd);
			String verifyCode =( System.currentTimeMillis()+"").substring(7,13);  
			String message = "您的验证码为" +verifyCode+" ,请在找回密码页面输入以完成找回密码的操作。【踏客社区】";
		    try
		    {
		      message = URLEncoder.encode(message, "GBK");
		    }
		    catch (UnsupportedEncodingException e) {
		      e.printStackTrace();
		    }
		    String r = HttpRequestProxy.doPost("http://221.181.73.88/sms/SmsSendInstance.do?accountId=" + accountId + "&pwd=" + newpwd + "&mobs=" + loginName + "&msg=" + message + "&timestamp=" + timestamp, new HashMap(), "utf-8");
			SmgRegVerifycodeRecord record = new  SmgRegVerifycodeRecord();
			record.setMobileNumber(loginName);
			record.setTimestamp(timestamp);
			record.setVerifycode(verifyCode);
			smgRegVerifycodeRecordManager.save(record);
		    resultMap.put("state", "1");
		    resultMap.put("desc", "验证码已发送");
		  } catch (Exception e) {
		    e.printStackTrace();
		    resultMap.put("state", "-99");
		    resultMap.put("desc", "运行时错误");
		   
		  }
		  return resultMap;
		}
	@RequestMapping(value="/findpassword")
	public @ResponseBody Map<String,Object> findPassword(@RequestParam String loginName
			,@RequestParam String verifyCode,@RequestParam String timestamp){
		String preRegUrl = REG_LOGIN_SEVICE_URL+"/account/findPwd.action";
		Map<String,Object> paramMap = new HashMap<String,Object>();
		int type = getRegTargetType(loginName);
		Map<String,Object> map = new HashMap<String,Object>();
		if ( type == 0 ){
			map.put("state",Constant.ERROR_STATE);
			map.put("desc","请输入正确的手机号码或者邮箱");
			return map;
		}
		SmgRegVerifycodeRecord record =   smgRegVerifycodeRecordManager.getByVerifyCodeAndTimeStampAndMobileNumber(verifyCode,timestamp,loginName);
		if ( record == null){
			map.put("state",Constant.ERROR_STATE);
			map.put("desc","您输入的验证码不正确或者已过期,请重新点击发送验证码按钮发送验证码");
			return map;
		}
		paramMap.put("type",type);
		paramMap.put("target",loginName);
		Gson gson = new Gson();
		String param = gson.toJson(paramMap);
		preRegUrl = preRegUrl +"?param="+param;
		logger.debug(preRegUrl);
		String  result = HttpRequestProxy.doGet(preRegUrl,recvEncoding);
		Map<String,String> resultMap = GsonUtil.getMapByJsonString(result);
		if ( resultMap.get("resultCode").equals("1")){
			map.put("state",Constant.ERROR_STATE);
			map.put("desc",resultMap.get("resultMsg"));
		}else{
			map.put("state",Constant.SUCCESS_STATE);
			if (type == 1){
				map.put("desc","新密码已经发送你的手机中,请注意查收");
			}else{
				map.put("desc","新密码已经发送你的邮箱中,请注意查收");
			}
		}
	
		return map;
	}
	@RequestMapping(value="/findpasswordwithoutverifycode")
	public @ResponseBody Map<String,Object> findPasswordWithoutVerifyCode(@RequestParam String loginName
			){
		String preRegUrl = REG_LOGIN_SEVICE_URL+"/account/findPwd.action";
		Map<String,Object> paramMap = new HashMap<String,Object>();
		int type = getRegTargetType(loginName);
		Map<String,Object> map = new HashMap<String,Object>();
		if ( type == 0 ){
			map.put("state",Constant.ERROR_STATE);
			map.put("desc","请输入正确的手机号码或者邮箱");
			return map;
		}
		paramMap.put("type",type);
		paramMap.put("target",loginName);
		Gson gson = new Gson();
		String param = gson.toJson(paramMap);
		preRegUrl = preRegUrl +"?param="+param;
		logger.debug(preRegUrl);
		String  result = HttpRequestProxy.doGet(preRegUrl,recvEncoding);
		Map<String,String> resultMap = GsonUtil.getMapByJsonString(result);
		if ( resultMap.get("resultCode").equals("1")){
			map.put("state",Constant.ERROR_STATE);
			map.put("desc",resultMap.get("resultMsg"));
		}else{
			map.put("state",Constant.SUCCESS_STATE);
			if (type == 1){
				map.put("desc","新密码已经发送你的手机中,请注意查收");
			}else{
				map.put("desc","新密码已经发送你的邮箱中,请注意查收");
			}
		}
	
		return map;
	}
  @RequestMapping({"/template"})
  @ResponseBody
  public Map<String, Object> template(@RequestParam String type, @RequestParam String cont)
  {
    Map resultMap = new HashMap();
    try {
      resultMap.put("state", "1");
      resultMap.put("desc", "调用接口成功");
    } catch (Exception e) {
      e.printStackTrace();
      resultMap.put("state", "-99");
      resultMap.put("desc", "运行时错误");
    }
    return null;
  }
 
}
